import React, {useEffect, useState} from 'react';
import {Alert, Dimensions, Text, ToastAndroid, View} from 'react-native';

import LoginView from '../views/LoginView';
import ImageConstants from '../resources/ImageConstants';
import LinearGradient from 'react-native-linear-gradient';
import SelectProductView from '../views/SelectProductView';
import _ from 'lodash';
import withSerialPort from './SerialPortBoxPage';
import {get, post} from '../http/http';
import ModalViewUtil from '../components/ModalViewUtil';
import Row from '../components/Row';
import ColorButton from '../components/ColorButton';
import AutoSizingImage from '../components/AutoSizingImage';
import config from '../config/config';
import {goBack} from '../utils/RootNavigation';
import {useSelector} from 'react-redux';
import BoxProductsView from '../views/BoxProductsView';
import {ALERT_TYPE, Dialog, Toast} from 'react-native-alert-notification';
const WIN_WIDTH = Dimensions.get('window').width;

const CabinetProductsPage = props => {
  const [products, setProducts] = useState([]);
  const user = useSelector(state => state.root.user);
  useEffect(() => {
    props.loadData();
    user.userType === 0 && queryUserProducts();
  }, []);
  const materialCabinetId = props.route.params.materialCabinetId;

  const managerTakeProducts = () => {
    ModalViewUtil.showFromCenter(
      <BoxProductsView
        openBox={item => {
          if (parseInt(`${item.relNum}`, 10) <= 16) {
            item.address = '01';
            item.number = item.relNum;
          } else if (parseInt(`${item.relNum}`, 10) <= 40) {
            item.address = '02';
            item.number = parseInt(`${item.relNum}`, 10) - 16;
          } else {
            item.number = parseInt(`${item.relNum}`, 10) - 40;
            item.address = '03';
          }

          unlockBox(item, () => {});
        }}
      />,
    );
  };

  const queryUserProducts = () => {
    const handlerClick = _.debounce(async (product, completion) => {
      try {
        const {data} = await post(
          '/assets/materialCabinet/api/materialCabinetTake',
          {
            deviceId: config.DEVICE_ID,
            orderId: product.orderId,
          },
        );

        if (parseInt(`${data.relNum}`, 10) <= 16) {
          data.address = '01';
          data.number = data.relNum;
        } else if (parseInt(`${data.relNum}`, 10) <= 40) {
          data.address = '02';
          data.number = parseInt(`${data.relNum}`, 10) - 16;
        } else {
          data.number = parseInt(`${data.relNum}`, 10) - 40;
          data.address = '03';
        }
        unlockBox(data, completion);
      } catch (error) {
        Dialog.show({
          type: ALERT_TYPE.DANGER,
          title: '提醒',
          textBody: error.message,
          closeOnOverlayTap: true,
          autoClose: 2000, // or time in ms
        });
      }
    }, 500);
    get('/assets/assetsReserveOrder/api/getUserAssetsReserveOrderList', {
      materialCabinetId: materialCabinetId,
      grantWay: 3,
      orderStates: '10,20,25',
    }).then(res => {
      console.log('------>');
      console.log(JSON.stringify(res.data.data));
      if (res.data) {
        setProducts(res.data.data);
        if (res.data.data && res.data.data.length > 0) {
          setTimeout(() => {
            // 显示选择柜格取物界面
            ModalViewUtil.showFromCenter(
              <SelectProductView
                products={res.data.data}
                onManagerPress={async () => {
                  console.log('onManagerPress');
                  ModalViewUtil.dismissBottomView();
                  setTimeout(() => {
                    managerTakeProducts();
                  }, 300);
                }}
                onProductSelect={(product, completion) => {
                  handlerClick(product, completion);
                }}
                onClose={() => {
                  ModalViewUtil.dismissView();
                  props.navigation.goBack();
                }}
              />,
              true,
            );
          }, 500);
        } else {
          setProducts([]);
          props.checkBoxManager &&
            props.checkBoxManager(manager => {
              if (manager) {
                Alert.alert('提示', '您没有可取用的柜格', [
                  {text: '退出', onPress: () => props.navigation.goBack()},
                  {
                    text: '管理员取件',
                    onPress: () => {
                      managerTakeProducts();
                    },
                  },
                ]);
              } else {
                Dialog.show({
                  type: ALERT_TYPE.DANGER,
                  title: '提醒',
                  textBody: '您没有可取用的柜格',
                  closeOnOverlayTap: true,
                  autoClose: 2000, // or time in ms
                });
                props.navigation.goBack();
              }
            });
        }
      } else {
        setProducts([]);
        props.checkBoxManager &&
          props.checkBoxManager(manager => {
            if (manager) {
              Alert.alert('提示', '您没有可取用的柜格', [
                {text: '退出', onPress: () => props.navigation.goBack()},
                {
                  text: '管理员取件',
                  onPress: () => {
                    managerTakeProducts();
                  },
                },
              ]);
            } else {
              Dialog.show({
                type: ALERT_TYPE.DANGER,
                title: '提醒',
                textBody: '您没有可取用的柜格',
                closeOnOverlayTap: true,
                autoClose: 2000, // or time in ms
              });
            }
          });
      }
    });
  };

  const renderItem = ({item, index}, flex) => {
    if (item) {
      return (
        <View
          style={{
            width: '95%',
            marginLeft: 10,
            marginTop: 10,
            alignItems: 'stretch',
            borderWidth: 2,
            borderColor: '#aaa',
            borderRadius: 8,
            flex,
            overflow: 'hidden',
          }}>
          <View
            style={{
              alignSelf: 'flex-end',
              backgroundColor: item.relState ? '#22895B' : '#C1C0BF',
              borderBottomLeftRadius: 15,
              width: 40,
              height: 30,
            }}>
            <Text
              style={{
                textAlign: 'center',
                fontSize: 20,
                fontWeight: 'bold',
                color: 'white',
              }}>
              {item.relNum}
            </Text>
          </View>

          <Row style={{flex: 1}} />
          <LinearGradient
            colors={[
              item.relState ? '#027042' : '#626060',
              item.relState ? '#53AF82' : '#C7C7C7',
            ]}
            start={{x: 0, y: 0}}
            end={{x: 1, y: 0}}>
            <ColorButton
              style={{fontSize: 20, fontWeight: 'bold'}}
              height={30}
              disabled={!item.relState}
              backgroundColor={'transparent'}
              onPress={async () => {
                getProductFromBox(item);
              }}>
              {item.relState ? '取用' : '空闲'}
            </ColorButton>
          </LinearGradient>
        </View>
      );
    } else {
      return (
        <View
          style={{
            width: '95%',
            marginLeft: 10,
            marginTop: 10,
            alignItems: 'stretch',
            borderWidth: 2,
            borderColor: '#aaa',
            borderRadius: 8,
            flex,
            overflow: 'hidden',
          }}
        />
      );
    }
  };

  const renderContent = () => {
    return (
      <View style={{flex: 1, width: '100%', alignItems: 'center'}}>
        <AutoSizingImage
          source={ImageConstants.ICON_CABNET_TOP}
          width={'100%'}
          style={{marginTop: -120}}
        />
        {props.data.length > 0 ? (
          <Row style={{flex: 1, marginTop: 0}}>
            <View style={{flex: 1}}>
              {renderItem({item: props.data[0], index: 0}, 6)}
              {renderItem({item: props.data[1], index: 0}, 2)}
              {renderItem({item: props.data[2], index: 0}, 2)}
              {renderItem({item: props.data[3], index: 0}, 2)}
            </View>
            {[0, 1, 2, 3, 4].map(value => {
              return (
                <View style={{flex: 1}}>
                  {props.data
                    .slice(12 * value + 4, 12 * value + 4 + 11)
                    .map((item, index) => {
                      return renderItem(
                        {item: item, index: 12 * value + 4 + index},
                        1,
                      );
                    })}
                  {renderItem(
                    {
                      item: props.data[12 * value + 4 + 11],
                      index: 12 * value + 4 + 11,
                    },
                    2,
                  )}
                </View>
              );
            })}
          </Row>
        ) : null}
      </View>
    );
  };

  const getProductFromBox = item => {
    let value = parseInt(`${item.number}`, 10).toString(16);
    if (value.length === 1) {
      value = '0' + value;
    }
    console.log('item:', item);
    props.whetherBoxIsLock(item.address, value, async open => {
      if (open) {
        ToastAndroid.show('请先关闭柜门', ToastAndroid.SHORT);
      } else {
        if (item.relState) {
          try {
            await get(
              '/assets/materialCabinet/api/getAdminMaterialCabinetIsTake',
              {
                warehousingId: item.warehousingId,
              },
            );
            await get('/assets/materialCabinet/api/adminMaterialCabinetTake', {
              deviceId: item.warehousingId,
              relId: item.relId,
            });
            ToastAndroid.show('取用成功', ToastAndroid.SHORT);
            props.openBox(item, () => {
              props.loadData();
              props.checkLockState(item.address, value);
            });
          } catch (error) {
            Dialog.show({
              type: ALERT_TYPE.DANGER,
              title: '提醒',
              textBody: error.message,
              closeOnOverlayTap: true,
              autoClose: 2000, // or time in ms
            });
            // ToastAndroid.show(error.message, ToastAndroid.SHORT);
          }
        }
      }
    });
  };

  const unlockBox = (item, completion) => {
    let value = parseInt(`${item.number}`, 10).toString(16);
    if (value.length === 1) {
      value = '0' + value;
    }

    props.whetherBoxIsLock(item.address, value, async open => {
      if (open) {
        ToastAndroid.show('请先关闭柜门', ToastAndroid.SHORT);
      } else {
        try {
          await post(
            '/assets/materialCabinetOperation/api/materialCabinetOperationSave?route=assets',
            {
              relId: item.relId,
              userPagersId: null,
            },
            true,
          );
          completion && completion();
          if (props.data.find(v => v.relId === item.relId)) {
            props.data.find(v => v.relId === item.relId).relState = 0;
          }
          props.openBox(item, () => {
            props.checkLockState(item.address, value);
          });
        } catch (error) {
          ToastAndroid.show(error.message, ToastAndroid.SHORT);
        }
      }
    });
  };

  return <View style={{flex: 1}}>{renderContent()}</View>;
};

export default withSerialPort(CabinetProductsPage);
